import { Button, Space, Toast, Form, DotLoading } from "antd-mobile";
import { appNavigate, appTypeCheck, checkENV, checkENV2 } from "@/utils";
import requewt from "@/utils/requewt";
import { API, REDIRECT_TITLE, REDIRECT_WX_COVER, REDIRECT_WX_URL } from "@/config";
import { useEffect, useReducer, useRef, useState } from "react";
import callFeedback from "@/components/common/modalFeedback";
import { KvHeaderComp, KvContentComp, KvBrandComp } from "@/components/common";
import Router, { useRouter } from "next/router";
import { signIn, signOut } from "next-auth/react";
import { useCookies } from "react-cookie";
import * as gtag from '@/libs/gtag'
import useRecord from "@/components/pages/stores/useRecord";
import useApp from "@/stores/useApp";
import GameResult from "@/components/common/modalFeedback/game.result";


const pageName = "home";
const klassName = pageName.replace(/\./g, '-');

const LANDING_URL = `/landing`;
const TEST_TOKEN = `user:token:app:15685165:uni-4b906b7a051634d3e4b18275e9244919`


const ENV_MAP = {
  mini: {
    title: `小程序`,
    key: `mini`
  },
  app: {
    title: `APP`,
    key: `app`
  },
  test: {
    title: `测试`,
    key: `test`
  }
}

export default function Page(props) {
  const [env, setENV] = useState(undefined);
  const [loading, setLoading] = useState(true);
  const [cookies, setCookie] = useCookies(['name']);
  const [error, setError] = useState(undefined);
  const [envName, setENVName] = useState(undefined);
  const [showTest, setShowTest] = useState(false);

  const updateENV = useApp(state => state.updateENV);
  let timer, flag = 0;
  useEffect(() => {
    // wx?.miniProgram.postMessage({data:'test'})
    // new VConsole()
  },[])
  const compHandler = {
    login: async (body) => {
      const options = {
        method: `POST`,
        headers: {"Content-Type": "multipart/form-data"},
        body
      }
      const resp = await requewt(API.user.login, options);
      // const resp = {
      //   error_code: 999,
      //   msg: '此活动仅限车主参与'
      // }
      if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
        callFeedback({
          // title: ,
          hideClose:true,
          content: (
            <GameResult 
            // actions={}
              content={(
                <div className="result-modal">
            <div className="result-modal-text" dangerouslySetInnerHTML={{__html:  resp?.msg ||`登入失败!`}}>
              
        </div>
        
        <Button style={{marginTop:30}} key={`close`} onClick={e => {
              if(env === `mini`){
                wx?.miniProgram?.navigateBack()
              }
              else if(env === `app`) {
                window.UNIApp?.closePage()
              }
            }} 
                    className="modal-btn act-btn act-btn-primary">确 认</Button>
        
          </div>
              )}
            />
          ),
          actions: [
            
          ]
        })
        return null
      }
      const {token} = resp?.data;
      await setCookie('auth', token, {path: `/`, maxAge: 3600 * 24 * 7});

      // const resolve = await signIn("credentials", {token, redirect: false});
      await signIn("credentials", {token, redirect: false,position:body.source});
      // console.log(`resolve`, resolve)

      await Router.push(LANDING_URL);
    },
    testing: async () => {
      const uni_auth = TEST_TOKEN;
      const token = await compHandler.login({
        UNIAuth: uni_auth, source: `test`
      })
      console.log(token)
      if (!token) return
      await setCookie('auth', token, {path: `/`, maxAge: 3600 * 24 * 7});

      

      await Router.push(LANDING_URL)
    },
  }

  useEffect(() => {
    (async () => {
      setLoading(true);
      // debugger
      await waitForAuth();
    })()
  }, [])

  useEffect(() => {
    if (!ENV_MAP[env]) return setError(`请在引力域小程序或APP内打开!`);
    else setError(undefined);
    useMap[env].auth();
    updateENV(env);
    setENVName(ENV_MAP[env].title);

    if (env === `mini`) {
      const data = {
        title: REDIRECT_TITLE, // 分享标题
        path: `/pagesPublic/h5/detailH5?jumpDataVale=${encodeURIComponent(REDIRECT_WX_URL)}`,
        imageUrl: REDIRECT_WX_COVER
      }
      // alert(JSON.stringify(data))
      wx?.miniProgram.postMessage({data})
    }
  }, [env])

  const useMap = {
    mini: {
      auth: async e => {
        let {token: uni_token = TEST_TOKEN, source = 'mini', position='post'} = Router.query || {};
        if (!uni_token) {
          if (process.env.NODE_ENV === 'development') uni_token = TEST_TOKEN
          else return wx?.miniProgram.navigateTo({url: `/pages/user/auth`});
        }

        gtag.event({
          action: 'mini_login',
          category: 'Login',
          label: `${position||''}`,
        })

        const values = {UNIAuth: uni_token, source: source || `mini`, position};
        await compHandler.login(values, async () => {
          await Router.push(LANDING_URL)
        });
      }
    },
    app: {
      auth: async e => {
        const {position} = Router.query || {};
        const uni_token = window.UNIApp?.getToken();
        if (!uni_token) return window.UNIApp?.loginApp('logincallback');

        gtag.event({
          action: 'app_login',
          category: 'Login',
          label: `${position}`,
        })

        const values = {UNIAuth: uni_token, source: `app`, position}
        await compHandler.login(values, async () => {
          // window.backEventCallback = function () {
          //   alert("trgger callback");
          //   window.location.href = `/basketball716`;
          // }
          // window.UNIApp?.setBackEvent(function() {
          //     alert("trgger callback");
          //     window.location.href = `/basketball716`;
          // });
          await Router.push(LANDING_URL)
        });
      }
    },
    test: {
      auth: async e => {
        const {position} = Router.query || {};
        const values = {UNIAuth: TEST_TOKEN, source: `test`, position}

        gtag.event({
          action: 'test_login',
          category: 'Login',
          label: `${position}`,
        })

        await compHandler.login(values, async () => {
          await Router.push(LANDING_URL)
        });
      }
    }
  }

  const wait4Auth = async (ev) => {
    const resp = await checkENV2();
    updateENV(resp);
    setENV(resp)
  }

  const waitForAuth = async (ev) => {
    if (flag >= 30) {
      setLoading(false);
      setShowTest(`未检测到正式环境`);
      // Toast.show({duration: 3000, content: `授权失败！请保证网络畅通、并在引力域的APP或小程序中打开`});
      return
    }
    setTimeout(() => {
      if (ev) {
        setENV(ev);
        setLoading(false);
        return;
      }
      flag++;
      const resolve = checkENV();
      // console.log(`resolve`, resolve)
      waitForAuth(resolve);
    }, 100);
  };

  return (
    <>
      <div className={`p-${klassName} page page-start`}>
        <div className="inner">
          <KvBrandComp />

          <div className="position-center">

            <div className="kv-footer text-center" style={{color: `#fff`}}>
              {
                // [`mini`, `app`].includes(env) ?
                //   <>
                //     <DotLoading color='white' /> <span>{ENV_MAP[env].title} 登入中</span>
                //   </>
                //   :
                  showTest ?
                    <Space direction={`vertical`}>
                      {/*<span>{showTest}</span>*/}
                      <span>在引力域的APP或小程序中打开</span>
                      {/* <Button onClick={compHandler.testing}>测试登入</Button> */}
                    </Space>
                    :
                    <DotLoading color='white' />
              }
            </div>
          </div>
        </div>
      </div>

    </>

  )
}


Page.need2auth = false;
Page.pageName = pageName;